
import collections
import logging
import time

import dnf
import dnf.callback

logger = logging.getLogger("ocup")


class DnfDownloadCallback(dnf.callback.DownloadProgress):
    def __init__(self):
        self.downloads = collections.defaultdict(int)
        self.last_time = time.time()
        self.total_files = 0
        self.total_size = 0
        self.pkgno = 0
        self.total = 0
        self.pkg_name = None

    def _update(self):
        if self.last_time is not None:
            if time.time() - self.last_time < 3:
                if self.pkgno != self.total_files:
                    return
            else:
                self.last_time = time.time()

        downloaded = sum(self.downloads.values())
        msg = "Downloading {pkgno}/{total_files} RPMs,{pkg} {percent}% done.".format(
            pkgno=self.pkgno,
            total_files=self.total_files,
            pkg="" if self.pkg_name is None else self.pkg_name,
            percent=round(downloaded / self.total_size * 100, 2),
        )
        logger.info(msg)

    def end(self, payload, status, msg):
        # if status is None:
        #     self.pkg_name = msg
        nevra = str(payload)
        if status is dnf.callback.STATUS_OK:
            self.downloads[nevra] = payload.download_size
            self.pkgno += 1
            self._update()
            return
        if msg != "Already downloaded":
            logger.critical("Failed to download {} : {}".format(nevra, msg))

    def progress(self, payload, done):
        nevra = str(payload)
        self.downloads[nevra] = done
        self._update()

    def start(self, total_files, total_size, total_drpms=0):
        self.total_files = total_files
        self.total_size = total_size
